/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBeans.converter;

import facade.SuiLibFacade;
import facade.exception.NotExistingObjectException;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import managedBeans.coursesMB;
import valueObject.CategoryVO;

/**
 *
 * @author Juan Sebastian Hernández Serrato
 */
@ManagedBean(name = "catergoryVOConverter")
@RequestScoped
@FacesConverter(forClass=CategoryVO.class, value="categoryVOConverter")
public class CategoryVOConverter implements Converter{

    @EJB
    SuiLibFacade suiLibFacade;

    @Override
    public CategoryVO getAsObject(FacesContext context, UIComponent component, String value) {
        try {
            if(value == null || value.length() == 0)
                return null;
            coursesMB mB = (coursesMB)context.getApplication().getELResolver().getValue(context.getELContext(), null, "coursesMB");
            CategoryVO categoryVO = mB.getSuilibFacade().getCategoryVOById(getKey(value));/*suiLibFacade.getCategoryVOById(getKey(value));*/
            return categoryVO;
        } catch (NotExistingObjectException ex) {
            ex.printStackTrace();
            return null;
        }

    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        if(object == null)
            return null;
        if (object instanceof  CategoryVO) {
            CategoryVO categoryVO = (CategoryVO) object;
            return getStringKey(categoryVO.getId());
        }else{
            throw new IllegalArgumentException("Este convertidor sólo maneja instancias de CategoryVO, esta instancia es de tipo" + object.getClass().getName() );
        }
    }

    private String getStringKey(Integer value){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(value);
        return stringBuffer.toString();
    }

    private Integer getKey(String value){
        Integer key = Integer.valueOf(value);
        return key;
    }
}